package com.ssl.rms.controller;

import com.google.common.collect.Maps;
import com.ssl.rms.utils.DateUtils;
import com.ssl.rms.utils.JsonMapper;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 描述：basecontroller
 *
 * @author ssl
 * @create 2018/02/07 17:31
 */
public abstract class BaseController {
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 添加Model消息
     *
     * @param model
     * @param messages
     */
    protected void addMessage(Model model, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        model.addAttribute("message", sb.toString());
    }

    /**
     * 添加flash消息（redirect时候犯错错误消息）
     *
     * @param redirectAttributes
     * @param messages
     */
    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
    }

    /**
     * 返回json字符串
     *
     * @param response
     * @param object
     * @return
     */
    protected String renderString(HttpServletResponse response, Object object) {
        return renderString(response, JsonMapper.toJsonString(object), "application/json");
    }

    /**
     * 返回json字符串
     * @param response
     * @param string
     * @param type
     * @return
     */
    protected String renderString(HttpServletResponse response, String string, String type) {
        try {
            response.reset();
            response.setContentType(type);
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 处理成功
     *
     * @return
     */
    public Map<String, Object> SUCCESS() {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", "1");
        result.put("msg", "处理成功");
        return result;
    }

    /**
     * 处理成功
     *
     * @param code 成功代码
     * @param msg  消息提示
     * @return
     */
    public Map<String, Object> SUCCESS(String code, String msg) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", code);
        result.put("msg", msg);
        return result;
    }

    /**
     * 处理成功
     *
     * @param data 处理成功后返回的data
     * @return
     */
    public Map<String, Object> SUCCESS(Object data) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", "1");
        result.put("msg", "处理成功");
        result.put("data", data);
        return result;
    }

    /**
     * 处理成功
     *
     * @param code 成功代码
     * @param msg  消息提示
     * @param data 处理成功后返回的data
     * @return
     */
    public Map<String, Object> SUCCESS(String code, String msg, Object data) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", code);
        result.put("msg", msg);
        result.put("data", data);
        return result;
    }

    /**
     * 处理失败
     *
     * @return
     */
    public Map<String, Object> FAIL() {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", "500");
        result.put("msg", "处理失败");
        return result;
    }

    /**
     * 处理失败
     *
     * @param code 错误码
     * @param msg  错误提示
     * @return
     */
    public Map<String, Object> FAIL(String code, String msg) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", code);
        result.put("msg", msg);
        return result;
    }

    /**
     * 处理失败
     *
     * @param exception 异常消息提示
     * @return
     */
    public Map<String, Object> FAIL(Exception exception) {
        exception.printStackTrace();
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", "500");
        result.put("msg", exception.getMessage());
        return result;
    }

    /**
     * 处理失败
     *
     * @param code      错误码
     * @param exception 异常消息提示
     * @return
     */
    public Map<String, Object> FAIL(String code, Exception exception) {
        exception.printStackTrace();
        Map<String, Object> result = Maps.newHashMap();
        result.put("code", code);
        result.put("msg", exception.getMessage());
        return result;
    }
    /**
     * 初始化数据绑定
     * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击
     * 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }
            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }
}
